import Mock from 'mockjs' // 导入mockjs

import testMock from './testMock' // 测试mock数据模块
// 将所有模块放入mocks数组中
const mocks = [...testMock]

// 解析地址栏参数解析函数
const param2Obj = (url: string) => {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"').replace(/\+/g, ' ') + '"}')
}

// 关键！前端模式构建函数
export const mockXHR = () => {
  Mock['XHR'].prototype.proxy_send = Mock['XHR'].prototype.send
  Mock['XHR'].prototype.send = function () {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false
      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond: any) {
    return function (options: any) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        // https://expressjs.com/en/4x/api.html#req
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const item of mocks) {
    // flag为true时使用mock，false则使用后台服务
    if (item.flag) {
      Mock.mock(new RegExp(item.url), item.type || 'get', XHR2ExpressReqWrap(item.response))
    }
  }
}
